package com.boot.controller.blog;


import com.boot.controller.BaseController;
import com.boot.pojo.tables.HdjBlogLabel;
import com.boot.pojo.tables.records.HdjBlogCategoryRecord;
import com.boot.pojo.tables.records.HdjBlogLabelBlogRecord;
import com.boot.pojo.tables.records.HdjBlogLabelRecord;
import com.boot.pojo.tables.records.HdjBlogRecord;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.jooq.DSLContext;
import org.jooq.Result;
import org.omg.CORBA.INTERNAL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static com.boot.pojo.Tables.*;
import static com.boot.until.UtilBase.*;

/**
 * blog专用
 */
@RestController
@RequestMapping("blog")
public class BlogController extends BaseController {

    @Autowired
    private DSLContext create;


    /**
     * 查找标签
     * @param name
     * @return
     */
    public JsonObject getlabel(String name){
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT \n");
        sql.append(" blog_label.id \n");
        sql.append(" FROM  \n");
        sql.append(" hdj_blog_label AS blog_label\n");
        sql.append(" WHERE blog_label.`name`='"+name+"' \n");
        return dataChangeJsonObject ( create.fetchOne ( sql.toString () ));
    }

    /**
     * 获取博客的列表
     * @param page
     * @param pagenum
     * @return
     */
    public JsonArray getAllBlog(Integer page,Integer pagenum){
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT \n");
        sql.append(" blog.id AS `blogid`,blog.content,blog.text,blog.title ,\n");
        sql.append(" blog.address, \n");
        sql.append(" FROM_UNIXTIME(blog.create_time,'%Y-%m-%d %H:%i:%s') AS `createTime`,\n");
        sql.append(" huser.img_url,\n");
        sql.append(" huser.username,category.`name` AS `categoryName`\n");
        sql.append(" FROM hdj_blog blog\n");
        sql.append(" INNER JOIN hdj_blog_category category ON blog.category_id=category.id\n");
        sql.append(" INNER JOIN hdj_user huser ON huser.id=blog.user_id\n");
        sql.append(" ORDER BY blog.create_time DESC\n");
        if (0 != pagenum && 0 != page) {
            sql.append ( "LIMIT " ).append ( (page - 1) * pagenum ).append ( "," ).append ( pagenum );
        }
        log.info ( "【查找博客】={}",sql.toString () );
        return dataChangeJsonArray ( create.fetch ( sql.toString () ) );
    }

    /**
     * 根据blogID查找博客的详情
     * @param blogId
     * @return
     */
    public JsonObject getBlogByBlogId(Integer blogId){
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT \n");
        sql.append(" blog.id AS `id`,\n");
        sql.append(" blog.content \n");
        sql.append(" FROM hdj_blog blog\n");
        sql.append(" WHERE blog.id="+blogId+"\n");
        log.info ( "博客得详情={}",sql.toString () );
        return dataChangeJsonObject ( create.fetchOne ( sql.toString () ) );
    }

    /**
     * 获取某个博客的标签
     * @param blogId
     * @return
     */
    public JsonArray getBlogAlllabel(Integer blogId){
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT \n");
        sql.append(" hlabel.id,hlabel.`name` \n");
        sql.append(" FROM hdj_blog_label_blog hb \n");
        sql.append(" INNER JOIN hdj_blog_label hlabel ON hlabel.id=hb.label_id\n");
        sql.append(" WHERE hb.blog_id="+blogId+"\n");
        log.info ( "博客的详情={}",sql );
        return dataChangeJsonArray ( create.fetch ( sql.toString () ) );
    }

    /**
     * 获取博客的前10名的文章
     * @return
     */
    public JsonArray getTop_ten(){
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT \n");
        sql.append(" blog.id AS `id`, \n");
        sql.append(" blog.title \n");
        sql.append(" FROM hdj_blog blog\n");
        sql.append(" LIMIT 10\n");
        return dataChangeJsonArray ( create.fetch ( sql.toString () ) );
    }

    /**
     * 查找博客的主评论
     * @param blogId
     * @param page
     * @param pagenum
     * @return
     */
    public JsonArray getBlogMasterComment(Integer blogId,Integer page,Integer pagenum){
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT \n");
        sql.append(" hu.img_url AS `imgUrl`, \n");
        sql.append(" bm.id AS `commentId`, \n");
        sql.append(" bm.content AS `blogComment`,\n");
        sql.append(" hu.username AS `userName`,\n");
        sql.append(" FROM_UNIXTIME(bm.create_time,'%Y-%m-%d %H:%i:%s') AS `createTime`\n");
        sql.append(" FROM hdj_blog_comment bm\n");
        sql.append(" INNER JOIN hdj_user hu ON hu.id=bm.user_id\n");
        sql.append(" WHERE bm.blog_id="+blogId+"\n");
        if (0 != pagenum && 0 != page) {
            sql.append ( "LIMIT " ).append ( (page - 1) * pagenum ).append ( "," ).append ( pagenum );
        }
        return dataChangeJsonArray ( create.fetch ( sql.toString () ) );
    }


    /**
     * 获取评论下面子级评论
     * @param commentId
     * @return
     */
    public JsonArray getMasterCommentBranch(Integer commentId){
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT \n");
        sql.append(" hu.img_url AS `imgUrl`, \n");
        sql.append(" bm.id AS `commentId`, \n");
        sql.append(" bm.content AS `blogComment`,\n");
        sql.append(" hu.username AS `userName`,\n");
        sql.append(" FROM_UNIXTIME(bm.create_time,'%Y-%m-%d %H:%i:%s') AS `createTime`\n");
        sql.append(" FROM hdj_blog_comment bm\n");
        sql.append(" INNER JOIN hdj_user hu ON hu.id=bm.user_id\n");
        sql.append(" WHERE bm.reply_comment_id="+commentId+"\n");
        //log.info ( "【评论子查询】={}",sql.toString () );
        return dataChangeJsonArray ( create.fetch ( sql.toString () ) );
    }


    /**
     * 使用递归解析树深度遍历
     * @param commentId
     * @return
     */
    public JsonArray recursion(Integer commentId,JsonArray array){
        //第一遍查询
        JsonArray jsonArray=getMasterCommentBranch ( commentId );
        array.add ( jsonArray );
        //递归方法1
        for (int i = 0; i < jsonArray.size (); i++) {
            JsonObject item=jsonArray.get ( i ).getAsJsonObject ();
            //递归使用
            recursion ( getJsonAsInt ( item,"commentId" ),array);
        }
        //递归2(测试未成功)
       /* for (int i = 0; i < jsonArray.size (); i++) {
            JsonObject item=jsonArray.get ( i ).getAsJsonObject ();
            //在每个下面增加一个子节点
            JsonArray jsonElements=getMasterCommentBranch ( getJsonAsInt ( item,"commentId" ) );
            item.add ( "child",jsonElements);
            //递归使用
            recursion ( getJsonAsInt ( item,"commentId" ),array);
        }*/
        return array;
    }


    /**
     * 增加博客
     * @param param
     * @return
     */
    @RequestMapping(value = "add_blog",method = RequestMethod.POST,produces ="application/json;charset=utf-8")
    @Transactional
    public String addBlog(@RequestBody String param, HttpServletRequest request){
        try {
            JsonObject json=new JsonParser().parse ( param ).getAsJsonObject ();
            //获取参数
            Integer userId=getJsonAsInt ( json,"userId" );
            String content=getJsonAsString ( json,"content" );
            String text=getJsonAsString ( json,"text" );
            Integer category=getJsonAsInt ( json,"category" );
            String address=getCityNameByip ( getIpAddr ( request ) );
            String title=getJsonAsString ( json,"title" );
            //通过ip计算地址
            JsonArray label=json.get ( "label" ).getAsJsonArray ();
            //新增
            HdjBlogRecord blog=create.newRecord ( HDJ_BLOG );
            blog.setUserId ( userId );
            blog.setContent ( content );
            blog.setText ( text );
            blog.setCategoryId (category);
            blog.setAddress ( address );
            blog.setTitle ( title );
            blog.setCreateTime ( getCurrentTime ());
            blog.setUpdateTime ( getCurrentTime () );
            blog.insert ();
            //循环多对多增加标签
            for (int i = 0; i < label.size (); i++) {
                //根据标签名寻找其id(不存在时就新增)
                String name=label.get ( i).getAsString ();
                JsonObject resultLabel=getlabel ( name );
                if (!resultLabel.has ( "id" )){
                    //执行新增
                    HdjBlogLabelRecord labelRecord=create.newRecord ( HDJ_BLOG_LABEL );
                    labelRecord.setName ( name );
                    labelRecord.insert ();
                }
                //维护中间表
                Integer labelId=create.select ( HDJ_BLOG_LABEL.ID )
                        .from ( HDJ_BLOG_LABEL )
                        .where ( HDJ_BLOG_LABEL.NAME.eq ( name ) )
                        .fetchOne ()
                        .into ( Integer.class );
                HdjBlogLabelBlogRecord blogLabelBlogRecord=create.newRecord ( HDJ_BLOG_LABEL_BLOG );
                blogLabelBlogRecord.setBlogId ( blog.getId () );
                blogLabelBlogRecord.setLabelId ( labelId );
                blogLabelBlogRecord.insert ();
            }
            return success (1,"增加成功",blog.getId ());
        }catch (Exception e){
            e.printStackTrace ();
            return error ( -1,e.getMessage () );
        }
    }

    /**
     * 查找所有的分类
     * @return
     */
    @RequestMapping(value = "get_category",method = RequestMethod.POST,produces ="application/json;charset=utf-8")
    public String getAllCategory(){
        Result result=create.select (  )
                .from ( HDJ_BLOG_CATEGORY )
                .fetch ();
        JsonArray jsonArray=dataChangeJsonArray ( result );
     return success (jsonArray);
    }


    /**
     * 查找所有的标签
     * @return
     */
    @RequestMapping(value = "get_label",method = RequestMethod.POST,produces ="application/json;charset=utf-8")
    public String getAllLabel(){
        Result result=create.select (HDJ_BLOG_LABEL.NAME )
                .from ( HDJ_BLOG_LABEL )
                .fetch ();
        JsonArray jsonArray=dataChangeJsonArray ( result );
        //list分装改变属性
        List<String> list=new ArrayList<> (  );
        for (int i = 0; i < jsonArray.size (); i++) {
            list.add ( jsonArray.get ( i ).getAsJsonObject ().get ( "name" ).getAsString () );
        }
        return success (list);
    }

    /**
     * 获取所有的blog列表
     * @return
     */
    //@Cacheable(value = "allBlog",key = "#root.methodName")
    //@Cacheable(value = "allBlog")
    @RequestMapping(value = "get_all_blog",method = RequestMethod.POST,produces ="application/json;charset=utf-8")
    public String getAllBlog(@RequestBody String query){
        JsonObject json=new JsonParser ().parse ( query ).getAsJsonObject ();
        Integer page=getJsonAsInt ( json,"page" );
        Integer pagenum=getJsonAsInt ( json,"pagenum" );
        JsonArray blogArray=getAllBlog (page,pagenum);
        //循环查找标签
        for (int i = 0; i < blogArray.size (); i++) {
            JsonObject jsonObject=blogArray.get ( i ).getAsJsonObject ();
            Integer blogId=getJsonAsInt ( jsonObject,"blogid" );
            JsonArray labels=getBlogAlllabel ( blogId );
            jsonObject.add ( "labels",labels );
        }
        JsonObject result=new JsonObject ();
        Integer count=getAllBlog ( 0,0 ).size ();
        result.addProperty ( "count",count );
        result.add ( "rows",blogArray);
        return success (result);
    }

    /**
     * 根据博客id获取博客的详情
     * @return
     */
    @Cacheable("blogDetail")
    @RequestMapping(value = "getblog/{blogId}",method = RequestMethod.POST,produces ="application/json;charset=utf-8")
    public String getBlogById(@PathVariable Integer blogId){
        JsonObject result= getBlogByBlogId(blogId );
        return success (result);
    }

    /**
     * 获得博客的前10个文章
     * @return
     */
    @RequestMapping(value = "get_blog_top",method = RequestMethod.POST,produces ="application/json;charset=utf-8")
    public String getTop(){
        JsonArray result=getTop_ten ();
        return success (result);
    }

    /**
     * 获得博客评论树的深度解析
     * @return
     */
    @RequestMapping(value = "get_blog_comment",method = RequestMethod.POST,produces ="application/json;charset=utf-8")
    public String getBlogComment(@RequestBody String query){
        JsonObject json=new JsonParser ().parse ( query ).getAsJsonObject ();
        Integer blogId=getJsonAsInt ( json,"blogId" );
        Integer page=getJsonAsInt ( json,"page" );
        Integer pagrnum=getJsonAsInt ( json,"pagenum" );
        JsonArray result=getBlogMasterComment (  blogId,page,pagrnum);
        //循环查找子评论
        for (int i = 0; i < result.size (); i++) {
            JsonObject item=result.get ( i ).getAsJsonObject ();
            JsonArray array=new JsonArray ();
          JsonArray jsonElements=recursion ( getJsonAsInt ( item,"commentId" ),array);
            item.add ( "child", jsonElements );
        }
        return success (result);
    }

}
